#!/usr/bin/env python3
import crc
import sys
sys.path.append('..')
import struct
import time
from zircon.broker import Broker
from openpyxl import load_workbook
#from crc import Crc32
from zircon.flash import Flash

def print_help():
    help_msg = """
    Usage: python dcfg.py <EXCELFILE>
    Description:
    1. Python3.x should be used and should be in system executable pathes;
    2. <COMPORTNAME> is serial port name, e.g. 'COM1' in Windows, '/dev/ttyS0' in *nix;
    3. <EXCELFILE> is a excel file to be downloaded;
    """
    print(help_msg)


def main():
    if len(sys.argv) < 2:
        print_help()
        sys.exit()

    _broker = Broker()
    _broker.cdb_psw()
    flash = Flash(_broker)

    params_file = sys.argv[1]

    wb = load_workbook(filename = params_file, data_only = True)
    # DSP sheet Start
    dsp_sheet = wb['DSP']

    dsp_byte_arr = b''
    for i in dsp_sheet['E']:
        if(None != i.value) and ('Target Value' != i.value):
            dsp_byte_arr += struct.pack('<I', int(i.value))
            print(i.value)
    
    print(dsp_byte_arr)

    dac_byte_arr = b''
    dac_sheet = wb['DAC']
    for i in dac_sheet['E']:
        if(None != i.value) and ('Translate Val' != i.value):
            print(i.value)
            dac_byte_arr += struct.pack('<I', int(i.value))
            print(i.value)
    print(dac_byte_arr)

    data = dsp_byte_arr + dac_byte_arr
    print(data)
    crcVal = crc.main(data)
    length = len(data)
    reserved = ''.join('{:0110X}'.format( 0 ))#fill 55 bytes 0
    data = b'\x10' + \
           struct.pack('<I', length) + \
           struct.pack('<I', crcVal) + \
           bytearray.fromhex(reserved) + \
           dsp_byte_arr + \
           dac_byte_arr
    
    print(data)

    startAddr = 0x300000
    sectorNo = int(startAddr / 4096)
    i = 0
    while i < 4:
        flash.erase_sector(sectorNo + i)
        i += 1
    remaining = len(data)
    sended = 0
    BLOCK_SIZE = 128
    while remaining:
        if remaining >= BLOCK_SIZE:
            flash.program(startAddr+sended, data[sended:(sended+BLOCK_SIZE)])
            sended += BLOCK_SIZE
            remaining -= BLOCK_SIZE
        else:
            flash.program(startAddr+sended, data[sended:])
            sended += remaining
            remaining -= remaining


    print("Send complete\r\n")




if __name__ == '__main__':
    main()
